package com.zhiyin.seal.task;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.zhiyin.seal.entity.bo.ApprovalSmsBo;
import com.zhiyin.seal.service.ApplyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

@Component
public class SmsTask {
    @Autowired
    ApplyService applyService;

    @Scheduled(fixedDelay = 1000 * 10)
    public void waitApprovalTask(){
        List<ApprovalSmsBo> approvalSmsBoList = applyService.getWaitApprovalSms();
        if(approvalSmsBoList.size() > 0){
            // 发送批量短信
            sendApprovalNotes(approvalSmsBoList);
            // 更新短信状态
            List<Long> idList = approvalSmsBoList.stream().map(ApprovalSmsBo::getId).collect(Collectors.toList());
            if(idList.size() > 0){
                applyService.updateWaitApprovalSms(idList);
            }
        }
    }


    private void sendApprovalNotes(List<ApprovalSmsBo> approvalSmsBoList){
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "LTAI5tH6CeBtrbrQhkqjp775","rKlGC2gySJ6k92FxvGbb9eVctByLHY");
        IAcsClient client = new DefaultAcsClient(profile);
        for(ApprovalSmsBo approvalSmsBo : approvalSmsBoList){
            if(approvalSmsBo.getPhoneNumber() == null)
                continue;
            sendApprovalNotes(client,
                    approvalSmsBo.getPhoneNumber(),
                    approvalSmsBo.getNickName(),
                    approvalSmsBo.getReason(),
                    approvalSmsBo.getApplyPhone());
        }
    }

    private void sendApprovalNotes(IAcsClient client,String phoneNumber,String nickName,String reason,String applyPhone) {
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", phoneNumber);
        request.putQueryParameter("SignName", "鑫泽科智慧科技");
        request.putQueryParameter("TemplateCode", "SMS_269250756");
        String templateParam = "{\"name\":\""+nickName+"\",\"reason\":\""+reason+"\",\"phone\":\""+applyPhone+"\"}";
        request.putQueryParameter("TemplateParam", templateParam);
        try {
            client.getCommonResponse(request).getData();
        } catch (ClientException e) {
            e.printStackTrace();
        }
    }
}
